<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { createTableDataApi, deleteTableDataApi, getTableDataApi, updateTableDataApi, uploadFiles } from "@/api/table"
import { type GetTableData } from "@/api/table/types/table"
import { ElMessage, ElMessageBox, ElTable, type FormInstance, type FormRules } from "element-plus"
import { CirclePlus, Download, Refresh, RefreshRight, Search } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import * as XLSX from "xlsx"

defineOptions({
  // 命名当前组件
  name: "ElementPlus"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 增
const dialogVisible = ref<boolean>(false)
const uploadShow = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = reactive({
  joinSchool: "",
  userName: "",
  userAccount: "",
  userPassword: "",
  userRole: "",
  reviewRange: " "
})
const createAccount = () => {
  dialogVisible.value = true
  formData.userAccount = ""
  formData.joinSchool = ""
  formData.userRole = ""
  formData.userName = ""
  formData.userPassword = ""
  formData.reviewRange = " "
}
const formRules: FormRules = reactive({
  userAccount: [{ required: true, trigger: "blur", message: "请输入账号" }],
  userPassword: [{ required: true, trigger: "blur", message: "请输入密码" }]
})
const handleCreate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (valid) {
      if (currentUpdateId.value === undefined) {
        createTableDataApi(formData)
          .then(() => {
            ElMessage.success("新增成功")
            getTableData()
          })
          .finally(() => {
            dialogVisible.value = false
          })
      } else {
        updateTableDataApi({
          id: currentUpdateId.value,
          userAccount: formData.userAccount,
          userName: formData.userName,
          userRole: formData.userRole,
          joinSchool: formData.joinSchool,
          reviewRange: formData.reviewRange
        })
          .then(() => {
            ElMessage.success("修改成功")
            getTableData()
          })
          .finally(() => {
            dialogVisible.value = false
          })
      }
    } else {
      console.error("表单校验不通过", fields)
    }
  })
}
const resetForm = () => {
  currentUpdateId.value = undefined
  formData.userAccount = ""
  formData.userPassword = ""
}
//#endregion

//#region 删
const handleDelete = (row: GetTableData) => {
  ElMessageBox.confirm(`正在删除用户：${row.userAccount}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteTableDataApi({
      id: row.id
    }).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const currentUpdateId = ref<undefined | string>(undefined)
const handleUpdate = (row: GetTableData) => {
  currentUpdateId.value = row.id
  formData.userAccount = row.userAccount
  formData.joinSchool = row.joinSchool
  formData.userRole = row.userRole
  formData.userName = row.userName
  formData.userPassword = row.userPassword
  formData.reviewRange = row.reviewRange
  dialogVisible.value = true
}
//#endregion

//#region 查
const tableData = ref<GetTableData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  userRole: "",
  joinSchool: "",
  workTeam: ""
})
const getTableData = () => {
  loading.value = true
  getTableDataApi({
    current: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    joinSchool: searchData.joinSchool || undefined,
    workTeam: searchData.workTeam || undefined,
    userRole: searchData.userRole || undefined
    // userAccount: searchData.userAccount || undefined,
    // phone: searchData.phone || undefined
  })
    .then((res) => {
      paginationData.total = parseInt(res.data.total)
      tableData.value = res.data.records
      ElMessage.success("查询成功")
    })
    .catch(() => {
      tableData.value = []
      ElMessage.error("查询失败")
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

const options = [
  {
    value: "1",
    label: "思政科组"
  },
  {
    value: "2",
    label: "公共基础课程组(不含思政)"
    // disabled: true
  },
  {
    value: "3",
    label: "专业技能课程一组"
  },
  {
    value: "4",
    label: "专业技能课程二组"
  }
]

const useRole = [
  {
    value: "teacher",
    label: "教师"
  },
  {
    value: "judge",
    label: "评委"
  },
  {
    value: "admin",
    label: "管理员"
  }
]
const multipleSelection = ref<GetTableData[]>([])
const handleSelectionChange = (val: GetTableData[]) => {
  multipleSelection.value = val
}
const webDerive = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请选择要下载的用户")
    return
  }
  ElMessageBox.confirm("是否确认导出选中数据?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    const tableHeader = [
      ["身份", "学校", "姓名", "报名组别", "账号名"] //导出表头
    ] // 表格表头
    multipleSelection.value.forEach((item: any, index) => {
      options.forEach((ops) => {
        if (ops.value === item.workTeam) {
          item.workTeam = ops.label
        }
      })
      useRole.forEach((ops) => {
        if (ops.value === item.userRole) {
          item.userRole = ops.label
        }
      })
      let rowData = []
      //导出内容的字段
      rowData = [item.userRole, item.joinSchool, item.userName, item.workTeam, item.userAccount]
      tableHeader.push(rowData), index + 1
    })
    const workSheet = XLSX.utils.aoa_to_sheet(tableHeader)
    const bookNew = XLSX.utils.book_new()
    // 定义所有列的宽度
    const columnWidth = 20 // 你可以根据需要修改列宽度
    // 设置所有列的宽度
    workSheet["!cols"] = Array(tableHeader[0].length).fill({ wch: columnWidth })
    XLSX.utils.book_append_sheet(bookNew, workSheet, "评价信息") // 工作簿名称
    const name = "评价管理管理数据" + ".xlsx"
    XLSX.writeFile(bookNew, name) // 保存的文件名
  })
}
const fileList = ref<GetTableData[]>([])
// 文件超出个数限制时的钩子
const exceedFile = (files, fileList) => {
  ElMessage({
    message: `只能选择 ${limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个`,
    type: "warning",
    duration: 5 * 1000
  })
}
// 文件状态改变时的钩子
const fileChange = (file: any) => {
  console.log(file.raw)
  const extension = file.name.split(".")[1]
  const size = file.size / 1024 / 1024
  if (extension !== "csv" && extension !== "xlsx" && extension !== "xls") {
    return ElMessage.warning("只能上传后缀是csv/xlsx/xls的文件")
  }
  console.log(size)
  if (size > 10) {
    console.log(fileList)
    return ElMessage.warning("文件大小不得超过10M")
  } else {
    fileList.value.push(file.raw)
    console.log(fileList.value)
  }
}

// 文件上传成功时的钩子
const handleSuccess = (res, fileList) => {
  ElMessage({
    message: "文件上传成功",
    type: "success",
    duration: 3 * 1000
  })
}

// 文件上传失败时的钩子
const handleError = (err, fileList) => {
  ElMessage({
    message: err.errMsg ? err.message : "上传失败",
    type: "error",
    duration: 3 * 1000
  })
}
const UploadUrl = () => {
  // 因为action参数是必填项，我们使用二次确认进行文件上传时，直接填上传文件的url会因为没有参数导致api报404，
  // 所以这里将action设置为一个返回为空的方法就行，避免抛错
  return ""
}

const uploadFile = () => {
  if (fileList.value.length === 0) {
    ElMessage({
      message: "请上传文件",
      type: "warning",
      duration: 3 * 1000
    })
  } else {
    const form = new FormData()
    form.append("file", fileList.value[0])
    console.log(form.get("file"), "formData")
    uploadFiles(form).then(
      (res) => {
        if (res.code === 200) {
          handleSuccess(res, fileList)
          paginationData.total = parseInt(res.data.total)
          tableData.value = res.data.records
        } else {
          handleError(res, fileList)
          fileList.value = []
        }
      },
      (err) => {
        handleError(err, fileList)
        fileList.value = []
      }
    )
  }
}
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="userRole" label="身份">
          <el-select v-model="searchData.userRole" clearable placeholder="请选择" style="width: 240px">
            <el-option v-for="item in useRole" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="学校">
          <el-input v-model="searchData.joinSchool" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="报名组别">
          <el-select v-model="searchData.workTeam" clearable placeholder="请选择" style="width: 240px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="createAccount">新增用户</el-button>
          <el-button type="success" icon="download" @click="webDerive">下载模板</el-button>
          <el-button type="success" @click="uploadShow = true" icon="upload">立即上传</el-button>
        </div>
        <div>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="userRole" label="身份" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.userRole === 'teacher'" effect="plain">教师</el-tag>
              <el-tag v-if="scope.row.userRole === 'judge'" effect="plain">评委</el-tag>
              <el-tag v-if="scope.row.userRole === 'admin'" effect="plain">管理员</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="joinSchool" label="学校" align="center" />
          <el-table-column prop="userName" label="用户名" align="center" />
          <el-table-column prop="workTeam" label="报名组别" align="center">
            <template #default="scope">
              <div v-for="item in options">
                <el-tag v-if="scope.row.workTeam === item.value" effect="plain">{{ item.label }} </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="userAccount" label="账号" align="center" />
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog v-model="uploadShow" center title="上传用户账号信息">
      <el-upload
        drag
        :limit="limitNum"
        :auto-upload="false"
        :action="UploadUrl()"
        :before-upload="beforeUploadFile"
        :on-change="fileChange"
        :on-exceed="exceedFile"
        :on-success="handleSuccess"
        :on-error="handleError"
        :file-list="fileList"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>只能上传xlsx文件，且不超过10M</template>\
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="uploadFile">立即上传</el-button>
          <el-button @click="uploadShow = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增用户' : '修改用户'"
      @close="resetForm"
      width="30%"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="userName" label="姓名" v-if="formData.userName !== null">
          <el-input v-model="formData.userName" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="joinSchool" label="学校">
          <el-input v-model="formData.joinSchool" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="userRole" label="身份">
          <el-select v-model="formData.userRole" placeholder="请选择" style="width: 240px">
            <el-option v-for="item in useRole" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item
          prop="reviewRange"
          label="评选范围"
          v-if="formData.reviewRange === '' || formData.userRole === 'judge'"
        >
          <el-select v-model="formData.reviewRange" placeholder="请选择" style="width: 240px">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item prop="userAccount" label="账号">
          <el-input v-model="formData.userAccount" placeholder="请输入" />
        </el-form-item>

        <el-form-item prop="userPassword" label="密码">
          <el-input v-model="formData.userPassword" placeholder="请输入" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
